<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>主函数</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/main_function","wgTitle":"cpp/language/main function","wgCurRevisionId":73271,"wgArticleId":8095,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":[],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/main_function","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><style type="text/css">/*<![CDATA[*/
.source-text {line-height: normal;}
.source-text li, .source-text pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for text
 * CSS class: source-text, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.text.source-text .de1, .text.source-text .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.text.source-text  {font-family:monospace;}
.text.source-text .imp {font-weight: bold; color: red;}
.text.source-text li, .text.source-text .li1 {font-weight: normal; vertical-align:top;}
.text.source-text .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.text.source-text .li2 {font-weight: bold; vertical-align:top;}
.text.source-text .ln-xtra, .text.source-text li.ln-xtra, .text.source-text div.ln-xtra {background-color: #ffc;}
.text.source-text span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_main_function skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">主函数</h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../container.html" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="basic_concepts.html" title="cpp/language/basic concepts">基本概念</a><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em">
<tr class="t-nv"><td colspan="5"> <a href="../keywords.html" title="cpp/keyword"> 语言关键词</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="charset.html" title="cpp/language/charset"> 字符集与编码</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="translation_phases.html" title="cpp/language/translation phases"> 翻译阶段</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../comments.html" title="cpp/comment"> 注释</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <strong class="selflink"> <code>main()</code> 函数</strong> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="punctuators.html" title="cpp/language/punctuators"> 标点</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="name.html" title="cpp/language/identifiers"> 名字和标识符</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="incomplete_type.html" title="cpp/language/type"> 类型</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="types.html" title="cpp/language/types"> 基础类型</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="object.html" title="cpp/language/object"> 对象</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="scope.html" title="cpp/language/scope"> 作用域</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="lifetime.html" title="cpp/language/lifetime"> 对象生存期</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="storage_duration.html" title="cpp/language/storage duration"> 存储期与连接</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="definition.html" title="cpp/language/definition"> 定义和单一定义规则（ODR）</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="lookup.html" title="cpp/language/lookup"> 名字查找</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="qualified_lookup.html" title="cpp/language/qualified lookup"> 有限定名字查找</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="unqualified_lookup.html" title="cpp/language/unqualified lookup"> 无限定名字查找</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="as_if.html" title="cpp/language/as if"> “如同”规则</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="ub.html" title="cpp/language/ub"> 未定义行为</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="memory_model.html" title="cpp/language/memory model"> 内存模型</a> </td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>程序应当含有一个名为 <code><b>main</b></code> 的全局函数（主函数），它被指定为程序的启动点。它应当有下列形式之一：
</p>
<table class="t-sdsc-begin">

<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">int</span></span></span> <code><b>main</b></code> <code><b>()</b></code> <code><b>{</b></code> <span class="t-spar">函数体</span> <code><b>} </b></code>
</td>
<td> (1)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">int</span></span></span> <code><b>main</b></code> <code><b>(</b></code><span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">int</span></span></span> <span class="t-spar">argc</span><code><b>,</b></code> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">char</span></span></span> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="sy2">*</span></span></span><span class="t-spar">argv</span><span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="br0">[</span><span class="br0">]</span></span></span><code><b>)</b></code> <code><b>{</b></code> <span class="t-spar">函数体</span> <code><b>} </b></code>
</td>
<td> (2)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="coMULTI">/* 其他由实现定义的形式，返回类型为 int */</span></span></span>
</td>
<td> (3)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr></table>
<table class="t-par-begin">


<tr class="t-par">
<td>  argc
</td>
<td> -
</td>
<td>  非负数，表示从程序运行的环境传递给程序的实参个数。
</td></tr>
<tr class="t-par">
<td>  argv
</td>
<td> -
</td>
<td>  指针，指向包含 <span class="t-c"><span class="mw-geshi cpp source-cpp">argc <span class="sy2">+</span> <span class="nu0">1</span></span></span> 个指针的数组的首元素。数组末元素为空指针，若其前面有任何元素，则它们指向<a href="../string/multibyte.html" title="cpp/string/multibyte">空终止多字节字符串</a>，表示从执行环境传递给程序的若干参数。若 <span class="t-c"><span class="mw-geshi cpp source-cpp">argv<span class="br0">[</span><span class="nu0">0</span><span class="br0">]</span></span></span> 不是空指针，或等价地 <span class="t-c"><span class="mw-geshi cpp source-cpp">argc</span></span> &gt; 0 ，则它指向表示用于调用程序的名称的字符串，或空字符串。
</td></tr>
<tr class="t-par">
<td>  <span class="t-spar">函数体</span>
</td>
<td> -
</td>
<td>  主函数的函数体
</td></tr></table>
<p>名字 <code>argc</code> 和 <code>argv</code> ，以及形参的类型的表示方式是任取的：<span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">int</span> main<span class="br0">(</span><span class="kw4">int</span> ac, <span class="kw4">char</span><span class="sy2">**</span> av<span class="br0">)</span></span></span> 同样合法。
</p><p>主函数的一种常见的由实现定义的形式还有（除 <code>argc</code> 和 <code>argv</code> 之外的）第三个参数，类型为 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">char</span><span class="sy2">**</span></span></span> ，指向<a rel="nofollow" class="external text" href="https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html">指向<i>执行环境变量</i>的指针数组</a>。
</p>
<h3><span class="mw-headline" id=".E8.A7.A3.E9.87.8A">解释</span></h3>
<p>在程序启动时，主函数在<a href="initialization.html" title="cpp/language/initialization">初始化</a>具有静态<a href="storage_duration.html" title="cpp/language/storage duration">存储期</a>的非局部对象之后被调用。它是程序在<i>有宿主 (hosted)</i>环境（即有操作系统）中所指定的入口点。<i>自立</i>程序（启动加载器，操作系统内核，等等）的入口点则是由实现定义的。
</p><p>双形参形式的主函数的形参允许从执行环境中传递任意的多字节字符串（它们通常被称为<i>命令行参数</i>），各个指针 <code>argv[1] .. argv[argc-1]</code> 指向对应的每个字符串的第一个字符。指针 <code>argv[0]</code> 指向一个空终止多字节字符串的开头字符，该字符串表示用于执行该程序自身的名字（当执行环境不支持时为空字符串 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="st0">""</span></span></span>）。这些字符串是可修改的：比如可以用 <span class="t-lc"><a href="../string/byte/strtok.html" title="cpp/string/byte/strtok">std::strtok</a></span> 来使用它们，虽然对它们的修改并不会被传回给执行环境。由 <code>argv</code> 所指向的数组的大小至少为 <code>argc+1</code>，其最后一个元素 <code>argv[argc]</code> 保证为一个空指针。
</p><p>主函数具有几项特殊性质：
</p>
<div class="t-li1"><span class="t-li">1)</span> 不能在程序的任何地方使用它</div>
<div class="t-li2"><span class="t-li">a)</span> 尤其不能递归调用它</div>
<div class="t-li2"><span class="t-li">b)</span> 不能取其地址</div>
<div class="t-li1"><span class="t-li">2)</span> 不能预定义，不能重载：实际上，名字 <code>main</code> 在全局命名空间中对函数保留（虽然可以用作类、命名空间、枚举和非全局命名空间中的任何实体的名字，但不能在任何命名空间中将名为“main”的函数声明为具有 C <a href="language_linkage.html" title="cpp/language/language linkage">语言链接</a>）。</div>
<div class="t-li1"><span class="t-li">3)</span> 不能<span class="t-rev-inl t-since-cxx11"><span>定义为被弃置（ <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="sy1">=</span>delete<span class="sy4">;</span></span></span> ），或</span> <span><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></span></span>声明为具有 C <a href="language_linkage.html" title="cpp/language/language linkage">语言链接</a><span class="t-rev-inl t-since-cxx11"><span>、<a href="constexpr.html" title="cpp/language/constexpr"><code>constexpr</code></a></span> <span><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></span></span><span class="t-rev-inl t-since-cxx20"><span>、<a href="consteval.html" title="cpp/language/consteval"><code>consteval</code></a></span> <span><span class="t-mark-rev t-since-cxx20">(C++20 起)</span></span></span>、<a href="inline.html" title="cpp/language/inline"><code>inline</code></a> 或 <a href="static.html" title="cpp/language/static"><code>static</code></a>。</div>
<div class="t-li1"><span class="t-li">4)</span> 主函数的函数体不需要包含 <a href="return.html" title="cpp/language/return">return 语句</a>：当控制达到主函数体的末尾而未遇到返回语句时，其效果为执行 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">return</span> <span class="nu0">0</span><span class="sy4">;</span></span></span>。</div>
<div class="t-li1"><span class="t-li">5)</span> 执行返回（或当到达主函数体的末尾时的隐式返回）等价于先正常离开函数（这将销毁具有自动存储期的对象），然后用和 <a href="return.html" title="cpp/language/return">return</a> 相同的实参来调用 <span class="t-c"><span class="mw-geshi cpp source-cpp"><a href="../utility/program/exit.html"><span class="kw967">std::<span class="me2">exit</span></span></a></span></span>。（<span class="t-c"><span class="mw-geshi cpp source-cpp"><a href="../utility/program/exit.html"><span class="kw967">std::<span class="me2">exit</span></span></a></span></span> 随即销毁静态对象并终止程序）</div>
<div class="t-li1"><span class="t-li">6)</span> <span class="t-mark-rev t-since-cxx14">(C++14 起)</span> 主函数的返回类型不能被推导（不允许 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">auto</span> main<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>...</span></span>）。</div>
<div class="t-li1"><span class="t-li">7)</span> <span class="t-mark-rev t-since-cxx20">(C++20 起)</span> 主函数不能是<a href="coroutines.html" title="cpp/language/coroutines">协程</a>。</div>
<h3><span class="mw-headline" id=".E6.B3.A8.E8.A7.A3">注解</span></h3>
<p>如果以<a href="function-try-block.html" title="cpp/language/function-try-block">函数 try 块</a>定义主函数，则它捕捉不到（由隐含的 <span class="t-lc"><a href="../utility/program/exit.html" title="cpp/utility/program/exit">std::exit</a></span> 所销毁的）静态对象的析构函数所抛出的异常。
</p><p>将操作系统命令行上给定的参数转换为由 <code>argv</code> 所指代的多字节字符数组的方式，可能涉及到由实现定义的处理过程：
</p>
<ul><li> <a rel="nofollow" class="external text" href="https://msdn.microsoft.com/en-us/library/17w5ykft.aspx">分析 C++ 命令行参数</a> MSDN
</li><li> <a rel="nofollow" class="external text" href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01">Shell 介绍</a> POSIX
</li></ul>
<h3><span class="mw-headline" id=".E7.A4.BA.E4.BE.8B">示例</span></h3>
<div class="t-example"><p>演示如何通知程序：从哪里获得输入，向哪里写入结果。<br>一种可能的调用方式：<span class="t-c"><span class="mw-geshi cpp source-cpp">.<span class="sy2">/</span>convert table_in.<span class="me1">dat</span> table_out.<span class="me1">dat</span></span></span></p><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
<span class="co2">#include &lt;iomanip&gt;</span>
<span class="co2">#include &lt;cstdlib&gt;</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="kw4">int</span> argc, <span class="kw4">char</span> <span class="sy2">*</span>argv<span class="br0">[</span><span class="br0">]</span><span class="br0">)</span>
<span class="br0">{</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"argc == "</span> <span class="sy1">&lt;&lt;</span> argc <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
 
    <span class="kw1">for</span><span class="br0">(</span><span class="kw4">int</span> ndx<span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span> ndx <span class="sy3">!</span><span class="sy1">=</span> argc<span class="sy4">;</span> <span class="sy2">++</span>ndx<span class="br0">)</span> <span class="br0">{</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"argv["</span> <span class="sy1">&lt;&lt;</span> ndx <span class="sy1">&lt;&lt;</span> <span class="st0">"] == "</span> <span class="sy1">&lt;&lt;</span> <a href="../io/manip/quoted.html"><span class="kw1802">std::<span class="me2">quoted</span></span></a><span class="br0">(</span>argv<span class="br0">[</span>ndx<span class="br0">]</span><span class="br0">)</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
    <span class="br0">}</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"argv["</span> <span class="sy1">&lt;&lt;</span> argc <span class="sy1">&lt;&lt;</span> <span class="st0">"] == "</span>
              <span class="sy1">&lt;&lt;</span> <span class="kw1">static_cast</span><span class="sy1">&lt;</span><span class="kw4">void</span><span class="sy2">*</span><span class="sy1">&gt;</span><span class="br0">(</span>argv<span class="br0">[</span>argc<span class="br0">]</span><span class="br0">)</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
    <span class="coMULTI">/*...*/</span>
    <span class="kw1">return</span> argc <span class="sy1">==</span> <span class="nu0">3</span> <span class="sy4">?</span> <a href="../utility/program/EXIT_status.html"><span class="kw972">EXIT_SUCCESS</span></a> <span class="sy4">:</span> <a href="../utility/program/EXIT_status.html"><span class="kw973">EXIT_FAILURE</span></a><span class="sy4">;</span> <span class="co1">// 可选返回值</span>
<span class="br0">}</span></pre></div></div>
<p>可能的输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">argc == 3
argv[0] == "./convert"
argv[1] == "table_in.dat"
argv[2] == "table_out.dat"
argv[3] == 0</pre></div></div> 
</div>
<h3><span class="mw-headline" id=".E5.8F.82.E9.98.85">参阅</span></h3>
<table class="t-dsc-begin">

</table>

<!-- 
NewPP limit report
Preprocessor visited node count: 1813/1000000
Preprocessor generated node count: 5037/1000000
Post‐expand include size: 41160/2097152 bytes
Template argument size: 8800/2097152 bytes
Highest expansion depth: 13/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:8095-0!*!0!!zh!*!zh!* and timestamp 20211222034048 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/main_function&amp;oldid=73271">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/main_function&amp;oldid=73271</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/main_function">Online version</a></li><li>Offline version retrieved 2022-01-01 00:37.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2021年12月21日 (星期二) 19:40。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过12,473次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 0.073 secs. -->
	</body>
<!-- Cached 20211222045554 -->
</html>